package com.tianxinweb.interceptors;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tianxinweb.entity.LoginControlUrl;
import com.tianxinweb.mapper.LoginControlUrlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

@Component
public class LoginCheckInteceptor implements HandlerInterceptor {

	@Autowired
	private LoginControlUrlMapper controlUrlMapper;

	/**
	 * 调用目标方法直前调用，如果返回TRUE则后面的继续执行，否则结束
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {


		String  url=request.getServletPath().toString();
		String str[] = url.split("/");
		if(str.length>2) url = "/"+str[1]+"/"+str[2];

		//获取用户需要登录才能访问的url
		List<String> urls = (List<String>) request.getServletContext().getAttribute("urls");
		if(urls==null){
			List<LoginControlUrl> controlUrls = controlUrlMapper.selectList(null);
			urls = new ArrayList<>();//保存需登录才能访问的url
			for(LoginControlUrl controlUrl : controlUrls){
				urls.add(controlUrl.getUrl());
			}
			request.getServletContext().setAttribute("urls", urls);
		}
		if(urls.contains(url)){
			Integer userId = (Integer) WebUtils.getSessionAttribute(request,"userId");
			if(userId==null){
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json; charset=utf-8");
				PrintWriter writer = response.getWriter();
				writer.write("{\"code\":-2,\"msg\":\"请先登录!\"}");
				writer.close();
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * 调用目标方法之后，渲染视图之前调用
	 * 管理员日志操作拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView arg3)
			throws Exception {

	}
	
	/**
	 * 渲染视图之后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}
}
